#include"Server.h"
#include<cstdio>
#include<unistd.h>
#include"HandleRequest.h"
#include<fcntl.h>

extern MyServSocket MS;
MyEpoll::MyEpoll(){
    // 创建epoll实例
    epoll_fd = epoll_create1(0);
    if (epoll_fd == -1) {
        perror("epoll_create1");
        exit(EXIT_FAILURE);
    }

    // 将服务端socket加入监听
    ev.data.fd = MS.GetSocketfd();
    ev.events = EPOLLIN;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ev.data.fd, &ev) == -1) {
        perror("epoll_ctl");
        close(epoll_fd);
        exit(EXIT_FAILURE);
    }
}

MyEpoll::~MyEpoll(){
    close(epoll_fd);
}

void MyEpoll::add(const socketfd& sockfd, int events){
    // 将sockfd加入epoll监听
    ev.data.fd = sockfd;
    ev.events = EPOLLIN|EPOLLET;
    setnonblocking(sockfd);
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
        perror("epoll_ctl");
    }
}

void MyEpoll::remove(const socketfd& sockfd){
    // 从epoll监听中移除sockfd
    if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, sockfd, NULL) == -1) {
        perror("epoll_ctl");
    }
}

void MyEpoll::listen_events(){
    // 循环监听epoll事件
    while(1){
        nfds = epoll_wait(epoll_fd, events, MAX_CLIENTS, -1);
        if (nfds == -1) {
            perror("epoll_wait");
            continue; // 或者退出循环，根据需求决定
        }

        for(int i = 0; i < nfds; i++){
            if(events[i].data.fd == MS.GetSocketfd()){
                // 如果是服务端socket，则接受客户端连接
                sockaddr_in client_addr;
                socketfd client_fd;
                if (!MS.AcceptConnection(client_addr, client_fd)) {
                    perror("AcceptConnection");
                    continue;
                }
                add(client_fd, EPOLLIN | EPOLLET);
            }
            else if(events[i].events & EPOLLIN){
                // 如果是客户端socket，则接收数据
                string read_buf;
                if (!MS.RecieveFromClient(events[i].data.fd, read_buf)) {
                    PRINT_ERRNO_AND_STRERROR(errno, "RecieveFromClient");
                    continue;
                }
                if(!read_buf.empty()){
                    PRINTF_LOG_AND_DEBUG(LOG_NOTICE, "Received data from client: %s\n", read_buf.c_str());
                    handle_request(read_buf, events[i].data.fd);
                }
            }
        }
    }
}

// 创建epoll实例，监听服务端socket，循环监听epoll事件
void startServer(){
    MyEpoll myepoll;

    myepoll.listen_events();
}


void setnonblocking(const socketfd& sockfd){
    int flags = fcntl(sockfd, F_GETFL, 0);
    if (flags == -1) {
        perror("fcntl F_GETFL");
        return;
    }
    if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl F_SETFL");
    }
}



